SYSTEMD_DIR=/lib/systemd/system
GRPC_ROOT=pkg/daemon/mgrpc

MEDIUMKUBE_BINDIR=/usr/local/mediumkube/bin
MEDIUMKUBE_CNI_BIN=/usr/local/mediumkube/cni/bin
MEDIUMKUBE_CONF=/etc/mediumkube
MEDIUMKUBE_CNI_CONF=/etc/mediumkube/cni/conf
MEDIUMKUBE_RUN=/var/run/mediumkube

.PHONY: cni dnsmasq

dir:
	sudo mkdir -p $(MEDIUMKUBE_BINDIR) $(MEDIUMKUBE_CONF)  $(MEDIUMKUBE_CNI_BIN) $(MEDIUMKUBE_CNI_CONF) $(MEDIUMKUBE_RUN)

cni:
	echo "Building CNI plugins"
	cd build; if [ ! -d "mediumkube-cni-plugins" ]; then git clone https://gitee.com/xmbsmdsj/mediumkube-cni-plugins.git; fi
	cd build/mediumkube-cni-plugins; ./build_linux.sh
	sudo mkdir -p /
	sudo cp build/mediumkube-cni-plugins/bin/*  $(MEDIUMKUBE_BINDIR)/


dnsmasq:
	echo "Building dnsmasq"
	cd build; if [ ! -d "mediumkube-dnsmasq" ]; then git clone https://gitee.com/xmbsmdsj/mediumkube-dnsmasq; fi
	cd build/mediumkube-dnsmasq; sudo make clean install BINDIR=../context
	sudo cp build/context/dnsmasq $(MEDIUMKUBE_BINDIR)/mediumkube-dnsmasq

test:
	go clean -testcache
	go test ./tests/...

generate:
	protoc --go_out=. \
	--go_opt=paths=source_relative \
	 --go-grpc_out=. \
	 --go-grpc_opt=paths=source_relative \
	 daemon/mgrpc/domain.proto

mediumkube:
	go build -o build/mediumkube commands/main.go

mediumkubed:
	go build -o build/mediumkubed daemon/main.go

all: mediumkube mediumkubed

clean:
	sudo rm -rf build/*

install: dir mediumkube mediumkubed dnsmasq cni
	sudo cp context/* $(MEDIUMKUBE_BINDIR)/

	# Copy binary and default configuration files
	sudo cp build/mediumkube $(MEDIUMKUBE_BINDIR)/
	sudo cp build/mediumkubed $(MEDIUMKUBE_BINDIR)/
	sudo cp config.yaml $(MEDIUMKUBE_CONF)/config.yaml
	
	# Register systemd service
	sudo cp mediumkube.service.start.sh /usr/local/sbin && sudo chmod +x /usr/local/sbin/mediumkube.service.start.sh
	sudo cp mediumkube.service.stop.sh /usr/local/sbin && sudo chmod +x /usr/local/sbin/mediumkube.service.stop.sh
	sudo cp mediumkube.service $(SYSTEMD_DIR)/mediumkube.service
	sudo systemd-analyze verify $(SYSTEMD_DIR)/mediumkube.service

	# Reload and enable service
	sudo systemctl daemon-reload
	sudo systemctl enable mediumkube

.PHONY: stop
stop:
	sudo systemctl stop mediumkube

.PHONY: start
start:
	sudo systemctl start mediumkube	
